//
//  OAuthViewController.swift
//  weibo2
//
//  Created by xuwzh on 15/10/6.
//  Copyright © 2015年 xuwzh. All rights reserved.
//

import UIKit
import SVProgressHUD

class OAuthViewController: UIViewController, UIWebViewDelegate {
    
    let WB_Client_Id="1608977151"
    let WB_Redirect_Uri="http://baidu.com"
    let WB_Secret_Id="5400739433c6d90d5a9cbf54d698aa3e"
    
    //令牌
    //"access_token" = "2.004MJnBG49GtkB557c115f2c0e5TS4";
    
    
    
    
    ///webview属性
    var webView : UIWebView {
        
        return view as! UIWebView
        
    }
    
    ///登录页面的关闭按钮
    @IBAction func closeLoginView(sender: AnyObject) {
        
        dismissViewControllerAnimated(true, completion: nil)
        SVProgressHUD.dismiss()
    }
    
    ///加载登录页面
    private func loadOAuthPage(){
        
        let str="https://api.weibo.com/oauth2/authorize?client_id=" + WB_Client_Id + "&redirect_uri=" + WB_Redirect_Uri
        let url = NSURL(string: str )!
        
        webView.loadRequest(NSURLRequest(URL: url))
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
    }
    
    ///页面出现执行的方法
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        loadOAuthPage()
    }
    
    ///用户发送登录请求的时候，过滤用户请求的url，
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        print(request.URL)
        
        let urlString=request.URL!.absoluteString
        
        ///判断url是否加载的新浪页面
        if urlString.hasPrefix("https://api.weibo.com"){
            return true
        }
        
        ///过滤是否是跳转页面
        if !urlString.hasPrefix(WB_Redirect_Uri){
            print("=============" + urlString)
            return false
        }
        
        let codeStr="code="
        let query=request.URL!.query!
        
        print("query=====" + query)
        
        if query.hasPrefix(codeStr){
            
            let code = (query as NSString).substringFromIndex(codeStr.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
            print("code====" + code)
            getUserAccountToken(code)
            return true
            
        }else{
            
            closeLoginView(codeStr)
        }
        
        
        return false
    }
    
    ///获取用户的令牌
    private func getUserAccountToken(code: String){
        
        let parms =
            ["client_id":WB_Client_Id,
            "client_secret":WB_Secret_Id,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":WB_Redirect_Uri]
        
           ///保存用户的登录信息后，
           UserAccount.loadAccessToken(parms) { (account, error)  in
            
            print(error)
            ///更新全局的用户信息变量
            if (account != nil){
            print("==========================")
            sharedAccount = account
            }else
            {
               SVProgressHUD.showInfoWithStatus("网络不给力，请求数据失败。")
            }
            
        }
        
    }
    
    
    ///开始加载页面
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
        
    }
    
    ///页面加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
}
